package com.clas.liu.myapplication.view.activity.impl;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.info.InfoData;
import com.clas.liu.myapplication.model.entity.searchUser.SearchUser;
import com.clas.liu.myapplication.model.entity.searchUser.SearchUserData;
import com.clas.liu.myapplication.presenter.impl.BasePresenter;
import com.clas.liu.myapplication.presenter.impl.SearchPresenter;
import com.clas.liu.myapplication.view.activity.i.ISearchActivity;
import com.clas.liu.myapplication.view.adapter.HotSearchAdapter;
import com.clas.liu.myapplication.view.adapter.SearchFragmentAdapter;
import com.clas.liu.myapplication.view.fragment.impl.BaseFragment;
import com.clas.liu.myapplication.view.fragment.impl.SearchInfoFragment;
import com.clas.liu.myapplication.view.fragment.impl.SearchUserFragment;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liu on 2019/5/11.
 */

public class SearchActivity extends BaseActivity<SearchPresenter> implements View.OnClickListener, ISearchActivity{

    private ImageView back;
    private EditText imputEt;
    private ImageView clearIv;
    private ImageView hisClearIv;
    private TabLayout tableLayout;
    private ViewPager viewPager;
    private LinearLayout hisLayout;
    private LinearLayout resultLayout;
    private RecyclerView hotRv;
    private RecyclerView historyRv;

    private SearchFragmentAdapter fragmentAdapter;
    private HotSearchAdapter hotAdapter;
    private HotSearchAdapter historyAdapter;
    private List<BaseFragment> fragments;
    private List<String> hotKeys;
    private List<String> historyList;
    private String cur_key;
    private Handler handler;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        findView();
        init();
        setListener();
    }

    private void init() {
        handler = new Handler();
        mPresenter.getHotKeys();
        initTabLayout();
        initFragmentViewPager();
        initHistoryKeys();
    }
    private void initHistoryKeys() {
        historyList = SaveUtil.getSearchHistory(this);
        if (historyList == null) {
            historyList = new ArrayList<>();
        }
        historyAdapter = new HotSearchAdapter(this, historyList);
        historyRv.setAdapter(historyAdapter);
        historyRv.setLayoutManager(new FlexboxLayoutManager(this, FlexDirection.ROW, FlexWrap.WRAP));
    }

    private void initHotSearch() {
        hotAdapter = new HotSearchAdapter(this, hotKeys);
        hotRv.setAdapter(hotAdapter);
        hotRv.setLayoutManager(new FlexboxLayoutManager(this, FlexDirection.ROW, FlexWrap.WRAP));

    }

    private void initTabLayout() {
        tableLayout.setTabMode(TabLayout.MODE_FIXED);


    }

    public void initFragmentViewPager() {
        fragments = new ArrayList<>();
        fragments.add(new SearchInfoFragment());
        fragments.add(new SearchUserFragment());
        fragmentAdapter = new SearchFragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(fragmentAdapter);
        tableLayout.setupWithViewPager(viewPager);
//        tableLayout.setTabsFromPagerAdapter(fragmentAdapter);

    }

    private void setListener() {
        back.setOnClickListener(this);
        clearIv.setOnClickListener(this);
        hisClearIv.setOnClickListener(this);
        imputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!v.getText().toString().equals("")) {
                        beginSearch(imputEt.getText().toString());
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void beginSearch(String s) {
        saveSearchHistory(s);
        cur_key = s;
        ((SearchInfoFragment)(fragments.get(0))).setIsRefresh(true);
        ((SearchUserFragment)(fragments.get(1))).setIsRefresh(true);
        mPresenter.searchInfo(s,1,10);
        mPresenter.searchUser(s,1,10);
    }

    private void findView() {
        back = findViewById(R.id.search_back_bt);
        imputEt = findViewById(R.id.search_edit);
        clearIv = findViewById(R.id.search_clear);
        hisClearIv = findViewById(R.id.search_his_clear);
        hisLayout = findViewById(R.id.search_his_layout);
        tableLayout = findViewById(R.id.search_table_layout);
        viewPager = findViewById(R.id.search_viewpager);
        resultLayout = findViewById(R.id.search_result_layout);
        hotRv = findViewById(R.id.search_hot_rv);
        historyRv = findViewById(R.id.search_his_rv);
    }

    @Override
    protected SearchPresenter getPresenter() {
        return new SearchPresenter(this);
    }

    public void showSearchHistoryLayout() {
        imputEt.setText("");
        hisLayout.setVisibility(View.VISIBLE);
        resultLayout.setVisibility(View.GONE);
    }

    public void startSsearch(String s) {
        imputEt.setText(s);
        beginSearch(s);
    }

    private void saveSearchHistory(String s) {
        SaveUtil.saveSearchHister(this, s);
        if (historyList.size()==0) {
            historyList.add(s);
        }else  {
            if (!historyList.get(0).equals(s) && !historyList.contains(s)) {
                historyList.add(0,s);
            }
        }
        historyAdapter.updateList(historyList);

    }
    private void clearSearchHistory() {
        SaveUtil.clearSearchHistory(this);
        historyList = new ArrayList<>();
        historyAdapter.updateList(historyList);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_clear:
                showSearchHistoryLayout();
                break;
            case R.id.search_back_bt:
                finish();
                break;
            case R.id.search_his_clear:
                clearSearchHistory();
                break;
        }
    }


    @Override
    public void failBecauseNetReturn(int code) {
        showToast(code+"请求失败！", Toast.LENGTH_SHORT);
    }
    public void searchUser(String s, int page_no, int page_size) {
        if (page_no == 1)
            beginSearch(s);
        else
            mPresenter.searchUser(s,page_no,page_size);
    }

    public void searchInfo(String s, int page_no, int page_size) {
        if (page_no == 1)
            beginSearch(s);
        else
            mPresenter.searchInfo(s,page_no,page_size);
    }
    public String getsearchKey() {
        return cur_key;
    }

    @Override
    public void InfoReturn(int code, InfoData data) {
        if ( ((SearchInfoFragment)(fragments.get(0))).getHandler()==null)
            ((SearchInfoFragment)(fragments.get(0))).setHandler(handler);
        if (resultLayout.getVisibility()==View.GONE) {
            resultLayout.setVisibility(View.VISIBLE);
            hisLayout.setVisibility(View.GONE);
        }
        if (((SearchInfoFragment)(fragments.get(0)))!=null) {
            ((SearchInfoFragment)(fragments.get(0))).InfoReturn(code,data);
        }

    }

    @Override
    public void UserReturn(int code, SearchUserData data) {
        if ( ((SearchInfoFragment)(fragments.get(0))).getHandler()==null)
            ((SearchInfoFragment)(fragments.get(0))).setHandler(handler);
        if (resultLayout.getVisibility()==View.GONE) {
            resultLayout.setVisibility(View.VISIBLE);
            hisLayout.setVisibility(View.GONE);
        }
        if (((SearchUserFragment)(fragments.get(1)))!=null) {
            ((SearchUserFragment)(fragments.get(1))).InfoReturn(code,data);
        }

    }

    @Override
    public void hotKeysReturn(int code, List<String> keys) {
        hotKeys = keys;
        initHotSearch();
    }

    @Override
    public void onBackPressed() {
        if (resultLayout.getVisibility() == View.VISIBLE) {
            showSearchHistoryLayout();
        }else
            super.onBackPressed();
    }
}
